package mqlistener

import (
	log "ac-common-go/glog"
	"ac-julink/socket"
	"ac-julink/tool/data"
	hsjson "ac-julink/tool/json"
	"ac-julink/tool/procinfo"
	"ac-julink/tool/util"
	"errors"
	"strings"
	"time"
	//"github.com/jjeffery/stomp"
	"ac-julink/cache"
	"ac-julink/manager"
	"github.com/go-stomp/stomp"
)

func NewWgssListener() *WgssActiveMqListener {
	return &WgssActiveMqListener{}
}

type WgssActiveMqListener struct {
}

func (self *WgssActiveMqListener) OnReceive(msg *stomp.Message, context *cache.SyncContext, client *manager.AcRestClient) (err error) {
	timeStart := time.Now().UnixNano()
	defer func() {
		if pErr := recover(); pErr != nil {
			log.Errorf("WgssActiveMqListener OnReceive panic:%+v\n%s", pErr, util.PanicTrace())
		}
	}()
	if msg == nil || msg.Body == nil {
		return errors.New("stomp.Message invalid")
	}
	log.Infof("Wgss MQ OnReceive:%s", string(msg.Body))
	_fdid, _wifiidlist, _result, _msgid, err := DealWgssSceneMq(string(msg.Body), context, client)
	if err != nil {
		log.Errorf("DealWgctlCmdMq failed !%+v", err)
		return err
	}

	for _, ch := range _wifiidlist {
		socketSession := socket.SocketManager.SessionMgr.GetSession(_fdid[ch])
		if socketSession != nil {
			log.Infof("socketSession:[%s]", _fdid[ch])
			if strings.Compare(socketSession.WifiID(), ch) != 0 {
				log.Errorf("Not Find wifi[%s] Session! ", ch)
				continue
			}
			socketSession.SendMessage(_result[ch])
		} else {
			log.Errorf("Get [%s] socketSession failed !", _fdid[ch])
			continue
		}
		log.Warningf("RECORD-WgssMQ:%d,%s,%dms,err:%+v", _msgid, ch, (time.Now().UnixNano()-timeStart)/1e6, err)
	}

	return nil
}

// 处理WGSS场景指令MQ消息
func DealWgssSceneMq(_jsonstr string, context *cache.SyncContext, client *manager.AcRestClient) (wifisession map[string]int, wifidlist []string, reponse map[string]string, msgid int, err error) {
	var isHENC bool
	log.Infof("DealWgssSceneMq====>>")
	//1.解析MQ数据
	_sceneid, _wifiid, _devid, _devtype, _wifiidlist, _oprtype, _exetype, err := hsjson.MQParseMsgScene(_jsonstr)
	if err != nil {
		log.Errorf("MQParseMsgScene  failed! ", err)
		return wifisession, wifidlist, reponse, msgid, err
	}
	reponse = make(map[string]string, len(_wifiidlist))
	wifisession = make(map[string]int, len(_wifiidlist))
	//client := manager.GetClientFacade()
	//2.查询PS设备在线状态
	for _, ch := range _wifiidlist {
		var online int
		var sid string
		//var ip string
		var fdid int
		resp, err := client.GetWifiStats(ch)
		if err != nil {
			log.Errorf("GetWifiStats  failed! ", err)
			return wifisession, _wifiidlist, reponse, msgid, err
		} else {
			if value, ok := resp["stat"]; ok && value != nil {
				online = int(value.(float64))
			}
			if value, ok := resp["owner"]; ok && value != nil {
				sid = value.(string)
			}
			if value, ok := resp["netid"]; ok && value != nil {
				fdid = int(value.(float64))
			}

			if value, ok := resp["cbcEnable"]; ok && value != nil {
				isHENC = value.(bool)
			}
		}
		if len(sid) == 0 {
			log.Errorf("sid in cannot be empty for [%v]!", resp)
			continue
		}

		log.Infof("GetWifiStats online:%d,sid:%s,fdid:%d", online, sid, fdid)
		//3.判断设备是否在线,sid是否为此节点
		if online != 1 {
			log.Errorf("Wifiid [%s] offline !", ch)
			continue
		}

		if strings.Compare(data.Mysid, sid) != 0 {
			log.Infof("Device on other sid[%s]!", sid)
			continue
		}
		//4.组装下发JSON数据
		var _json string
		if _oprtype == 4 { //场景执行
			msgid = 504
			procinfo.AddCount(msgid)
			_json, err = hsjson.SceneExecuteJsonCreate(_sceneid, _wifiid, _devid, _devtype, _oprtype, _exetype)
			if err != nil {
				log.Errorf("CmdControlJsonCreate failed !", err)
				continue
			}
		} else { //场景变更
			msgid = 503
			procinfo.AddCount(msgid)
			_json, err = hsjson.SceneChangeJsonCreate(_sceneid, _oprtype)
			if err != nil {
				log.Errorf("CmdControlJsonCreate failed !", err)
				continue
			}
		}
		//6.根据wifiid,获取预制密钥
		pre_key, _ := client.GetPublicKey(ch, isHENC, context)
		log.Infof("pre_jey[%s]", pre_key)
		//7.pacakage msg,组装HS{}MD5\r\n格式数据包
		_msgResult := data.PackageMsg(_json, pre_key)

		reponse[ch] = _msgResult
		wifidlist = append(wifidlist, ch)
		wifisession[ch] = fdid
	}

	return wifisession, wifidlist, reponse, msgid, err
}
